package cong.cheng.thread;

//打印类或者资源类
class Printer{
    private int flag = 0;
    public synchronized void printA() throws InterruptedException {
        while (flag != 0){				//防止虚假唤醒，不能用if要用while
            this.wait();
        }
        System.out.println(Thread.currentThread().getName()+":"+(char) ('A'+flag));
        flag++;
        this.notifyAll();
    }
    public synchronized void printB() throws InterruptedException {
        while (flag == 0){
            this.wait();
        }
        System.out.println(Thread.currentThread().getName()+":"+(char) ('A'+flag));
        flag--;
        this.notifyAll();
    }
}
public class ThreadTest {
    public static void main(String[] args) {
        Printer printer = new Printer();
        new Thread(()->{
            for (int i = 0; i < 10; i++){
                try {
                    printer.printA();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Thread-1").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++){
                try {
                    printer.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Thread-2").start();
    }

}
